package chapter16.Practic;

import chapter16.BTNode;
import chapter16.LinkedBinaryTree;
import java.util.ArrayList;
import java.util.StringTokenizer;

/**
 * Created by 蜡笔小新丶 on 2017/10/24.
 */
public class Original extends LinkedBinaryTree{
    public BTNode creatTree(String str){
        StringTokenizer tokenizer = new StringTokenizer(str);
        String token;
        ArrayList<String> operList = new ArrayList<>();

        ArrayList<LinkedBinaryTree> numList = new ArrayList<>();
        while (tokenizer.hasMoreTokens()){
            token = tokenizer.nextToken();
            if(token.equals("(")){
                String str1 = "";
                while (true){
                    token = tokenizer.nextToken();
                    if (!token.equals(")"))
                        str1 += token + " ";
                    else break;
                }
                LinkedBinaryTree S = new LinkedBinaryTree();
                S.root = creatTree(str1);
                numList.add(S);
            }
            if(as(token)){
                operList.add(token);
            }else if(md(token)){
                LinkedBinaryTree left = numList.remove(numList.size()-1);
                String A = token;
                token = tokenizer.nextToken();
                if(!token.equals("(")) {
                    LinkedBinaryTree right = new LinkedBinaryTree(token);
                    LinkedBinaryTree node = new LinkedBinaryTree(A, left, right);
                    numList.add(node);
                }else {
                    String str1 = "";
                    while (true){
                        token = tokenizer.nextToken();
                        if (!token.equals(")"))
                            str1 += token + " ";
                        else break;
                    }
                    LinkedBinaryTree S = new LinkedBinaryTree();
                    S.root = creatTree(str1);
                    LinkedBinaryTree node = new LinkedBinaryTree(A,left,S);
                    numList.add(node);
                }
            }else
                numList.add(new LinkedBinaryTree(token));
        }
        while(operList.size()>0){
            LinkedBinaryTree left = numList.remove(0);
            LinkedBinaryTree right = numList.remove(0);
            String oper = operList.remove(0);

            LinkedBinaryTree node = new LinkedBinaryTree(oper,left,right);
            numList.add(0,node);
        }
        root = (numList.get(0)).root;

        return root;
    }

    private boolean as(String token){
        return (token.equals("+")||
                token.equals("-"));
    }

    private boolean md(String token){
        return (token.equals("*")||
                token.equals("/"));
    }

    public String Output(){
        String result = "";
        ArrayList<String> list = new ArrayList<>();
        root.postorder(list);
        for(String i : list){
            result += i+" ";
        }
        return result;
    }
}
